<template>
  <div class="search-suggestion">
    <van-cell icon="search" v-for="(item, index) in suggestions" :key="index" @click="onSearch(item)">
      <div slot="title" v-html="highlight(item)"></div>
    </van-cell>
  </div>
</template>

<script>
import { getSearchSuggestions } from '@/api/search.js'
// 按需加载有好处：只会把使用到的成员打包到结果中
import { debounce } from 'lodash'
export default {
  name: 'SearchSuggestion',
  data () {
    return {
      suggestions: [], // 联想建议数据列表
      htmlStr: 'Hello <span style="color: red">World</span>'
    }
  },
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  methods: {
    async loadSearchSuggestions (q) {
      try {
        const { data } = await getSearchSuggestions(q)
        this.suggestions = data.data.options
        console.log(this.suggestions)
        console.log(11)
      } catch {
        this.$toast('获取失败')
      }
    },
    // text: 原始字符串
    highlight (text) {
      // this.searchText 输入框的值
      const reg = new RegExp(this.searchText, 'gi')
      return text.replace(reg, `<span style="color: #3296fa">${this.searchText}</span>`)
    }
  },
  computed: {},
  watch: {
    searchText: {
      // 当 searchText 发生改变的时候就会调用 handler 函数
      // 注意：handler 函数名称是固定的
      // handler (value) {
      //   console.log(value)
      // },

      // debounce 函数
      // 参数1：一个函数
      // 参数2：延迟时间，单位是毫秒
      // 返回值：防抖之后的函数
      handler: debounce(function (value) {
        this.loadSearchSuggestions(value)
      }, 200),
      // handler (value) {
      //   this.loadSearchSuggestions(value)
      // },
      immediate: true // 该回调将会在侦听开始之后被立即调用
    }
  },
  filters: {},
  components: {},
  created () { },
  mounted () { }
}
</script>

<style scoped lang='less'>
.search-suggestion {
  /deep/ span.active {
    color: #3296fa;
  }
  /deep/.van-field__left-icon {
    .van-icon-search {
      color: #aaa !important;
    }
  }
}
</style>
